﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using AppFramework.DinosaursParkMes.DictionariesModel.IService;
using AppFramework.DinosaursParkMes.Material.Dto;
using AppFramework.DinosaursParkMes.MaterialModel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Minio;
using NPOI.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Snowflake.Core;
using System.Threading.Tasks;
using static NPOI.SS.Format.CellNumberFormatter;
using IdentityModel.Client;
using Microsoft.EntityFrameworkCore;
using AppFramework.Dto;
using AppFramework.Codingrule.Exporting;
using AppFramework.DinosaursParkMes.DomainService.CodingRule;
using AppFramework.DinosaursParkMes.ProductWork.Dto;
using AppFramework.DinosaursParkMes.CodingRuleModel;
using PayPalCheckoutSdk.Orders;
using Abp.Domain.Uow;

namespace AppFramework.DinosaursParkMes.Material
{
    public class MaterialAppService : AppFrameworkAppServiceBase, IMaterialAppService
    {
        private readonly IRepository<MaterialModel.Material> _repository;
        private readonly IRepository<MaterialModel.Materialtype> _repository2;
        private readonly IRepository<MaterialModel.MaterialProductImg> _repository3;
        private readonly IRepository<ProductWorkModels> productworkmodels; 
        private readonly IMaterialExcelExporter _excelExporter;
        private readonly ICodingruleManager _manager;

        public MaterialAppService(IRepository<MaterialModel.Material> repository, IRepository<Materialtype> repository2, IRepository<MaterialProductImg> repository3, IMaterialExcelExporter excelExporter, ICodingruleManager manager, IRepository<ProductWorkModels> productworkmodels)
        {
            _repository = repository;
            _repository2 = repository2;
            _repository3 = repository3;
            _excelExporter = excelExporter;
            _manager = manager;
            this.productworkmodels = productworkmodels;
        }

        /// <summary>
        /// 物料添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost,Route("AddMaterial")]
        [UnitOfWork] //不加这个特性也是 默认工作单元的——在一个数据库事务中进行提交
        public async Task<AddMaterialDTO> AddMaterial([FromBody]AddMaterialDTO dto)
        {
           
            var Materialmodel = ObjectMapper.Map<MaterialModel.Material>(dto);
            Materialmodel.Materialnumber = await _manager.GetCode("Material");
              await _repository.InsertAsync(Materialmodel);

            foreach (var item in dto.ImgChildren)
            {
                var MaterialProductImgmodel=ObjectMapper.Map<MaterialProductImg>(item);
                //ToDo:采用枚举
                MaterialProductImgmodel.Filetype = 1;
                MaterialProductImgmodel.Number = Materialmodel.Materialnumber;
                await _repository3.InsertAsync(MaterialProductImgmodel);
            }
            foreach (var item in dto.AccessoryChildren)
            {
                var MaterialProductImgmodel = ObjectMapper.Map<MaterialProductImg>(item);
                   MaterialProductImgmodel.Filetype = 0;
                   MaterialProductImgmodel.Number = Materialmodel.Materialnumber;
                await _repository3.InsertAsync(MaterialProductImgmodel);
            }
            return dto;
        }
        /// <summary>
        /// 物料分类列表
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet,Route("Materialtype")]
        public async  Task<dynamic> Materialtype()
        {
            var list = await  _repository2.GetAllListAsync();
            return Result(list);
        }
        /// <summary>
        /// 物料列表递归
        /// </summary>
        /// <returns></returns>
        public List<MaterialtypeShowDto> Result(List<Materialtype> list,int id=0)
        {
            var res=new List<MaterialtypeShowDto>();
            foreach (var item in list.Where(x=>x.Pid==id))
            {
                res.Add(new MaterialtypeShowDto() { value = item.Id, label = item.Name, children= Result(list,item.Id) });
            }
            return res.Count() > 0 ? res : null;
        }
       /// <summary>
       /// /物料详情
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
       /// <exception cref="NotImplementedException"></exception>
        [HttpGet, Route("SelectMaterialById")]
        public   MaterialParticulars SelectMaterialById(string id)
        {
            var res = new MaterialParticulars();
            var list = _repository.GetAllList().Where(x=>x.Materialnumber==id).FirstOrDefault();
            res = ObjectMapper.Map<MaterialParticulars>(list);
            var imglisr = _repository3.GetAllList().Where(x => x.Number == list.Materialnumber&&x.Filetype==1);
            res.ImgChildren = ObjectMapper.Map<List<ParticularsImgList>>(imglisr);
            var accessorylisr = _repository3.GetAllList().Where(x => x.Number == list.Materialnumber && x.Filetype == 0);
            res.AccessoryChildren = ObjectMapper.Map<List<ParticularsAccessorylist>>(accessorylisr);
            return res;
        }

        /// <summary>
        /// 物料列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>   
        [HttpGet, Route("ShowMaterial")]
        public async Task<PagedResultDto<MaterialResponseDTO>> ShowMaterial(MaterialSelectDTO dto)
        {
            var dtos = new PagedResultDto<MaterialResponseDTO>();
            var MaterialclassifyN = _repository2.GetAll();
            var list1 = _repository.GetAll();
            var list = from a in  list1
                       select new MaterialResponseDTO
                       {
                           Id = a.Id,
                           Name = a.Name,
                           MaterialclassifyName = MaterialclassifyN.Where(x=>x.Id== a.Materialclassify).FirstOrDefault().Name,
                           Materialnumber = a.Materialnumber,
                           MaterialProperty = a.MaterialProperty,
                           Materialtype = a.Materialtype,
                           Specificationsversion = a.Specificationsversion,
                           State = a.State == true ? "启用" : "禁用",
                           Unit = a.Unit,
                           Materialclassify = a.Materialclassify
                       };
            if (!string.IsNullOrEmpty(dto.Name))
            {
                list = list.Where(m => m.Name.Equals(dto.Name)||m.Materialnumber.Equals(dto.Name));
            }
            if (!string.IsNullOrEmpty(dto.Materialtype))
            {
                list = list.Where(a => a.Materialtype .Equals( dto.Materialtype));
            }
            if (dto.State != -1)
            {
                if (dto.State == 1)
                {
                    list = list.Where(m => m.State.Equals("启用"));
                }
                else
                {
                    list = list.Where(m => m.State.Equals("禁用"));
                }

            }
            if (dto.Materialclassify != -1)
            {
                list = list.Where(m => m.Materialclassify == dto.Materialclassify);
            }
            if (!string.IsNullOrEmpty(dto.MaterialProperty))
            {
                list = list.Where(m => m.MaterialProperty == dto.MaterialProperty);
            }
            dtos.TotalCount = list.Count();
            dtos.Items =   await  list.OrderByDescending(p => p.Id).Skip((dto.PageIndex - 1) * dto.PageSize).Take(dto.PageSize).ToListAsync();
            return dtos;
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet,Route("GetFileDto")]
        public async Task<FileDto> GetFileDto()
        {
            //获取表中所有的数据
            var query = await _repository.GetAll().AsNoTracking().ToListAsync ();
            ////获取物料分类数据
            var MaterialclassifyN = await _repository2.GetAll().AsNoTracking().ToListAsync();
            var data = ObjectMapper.Map<List<MaterialExcelDto>>(query);
            data.ForEach(p =>
            {
                p.State = p.State == "true" ? "启用" : "禁用";
                p.Materialclassify = MaterialclassifyN.FirstOrDefault(x => x.Id == Convert.ToInt32(p.Materialclassify)).Name;
            });
            var token = _excelExporter.ExportToFile(data);
            return token;
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet,Route("GetProductWorkModelsFile")]
        public async Task<FileDto> GetProductWorkModelsFile()
        {
            //获取表中所有的数据
            var query = await productworkmodels.GetAll().AsNoTracking().ToListAsync();
            ////获取物料分类数据
            var data = ObjectMapper.Map<List<ProductWorkExcelDto>>(query);
            data.ForEach(p =>
            {
                switch (p.State)
                {
                    case "WaitScheduled":
                        p.State = "待排产";
                        break;
                    case "NotStarted":
                        p.State = "未开始/";
                        break;
                    case "InProgress":
                        p.State = "进行中/";
                        break;
                    case "Completed":
                        p.State = "已完成/";
                        break;
                    case "Paused":
                        p.State = "已暂停/";
                        break;
                    case "Closed":
                        p.State = "已关闭/";
                        break;
                }
            });
            var token = _excelExporter.ProductWorkExcelExportToFile(data);
            return token;
        }
    }

}
